/*
 * Copyright 2013 Gernot.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package tuwien.big.formel0.webservice;

import at.ac.tuwien.big.we.highscore.Failure;
import at.ac.tuwien.big.we.highscore.PublishHighScoreEndpoint;
import at.ac.tuwien.big.we.highscore.PublishHighScoreService;
import at.ac.tuwien.big.we.highscore.data.HighScoreRequestType;
import at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.DescriptionType;
import at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.GameType;
import at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.TournamentType;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
 * @author Gernot
 */
public class HighscorePublisher {
    private static final PublishHighScoreService service = new PublishHighScoreService();
    private static PublishHighScoreEndpoint endpoint = service.getPublishHighScorePort();
    /**
     * Do not instantiate, static class
     */
    private HighscorePublisher(){
        
    }
    /**
     * Translate m/w to MALE FEMALE, if error then MALE
     * @param sex
     * @return 
     */
    private static String getGenderStr(String sex){
        if (sex!=null){
            if (sex.equals("w")) {
                return "FEMALE";
            }
        }
        return "MALE"; 
    }
    
    private static TournamentType.Players.Player PlayerToXMLPlayer( tuwien.big.formel0.entities.Player ply) throws DatatypeConfigurationException, ParseException{
        TournamentType.Players.Player player = new TournamentType.Players.Player();
        
        
            player.setUsername(ply.getName());
            player.setGender(getGenderStr(ply.getSex()));

           // player.setUsername("Test");
           // player.setGender("MALE");

            //Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, "GENDER", ply.getSex());

            if (ply.getBirthday() != null) {

                GregorianCalendar gc = new GregorianCalendar(); //Current Time

                DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
                Date date = df.parse(ply.getBirthday()); //"01.04.1984");//
                gc.setTime(date);

                XMLGregorianCalendar bday = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);

                player.setDateOfBirth(bday);
            } else {
                Logger.getLogger(HighscorePublisher.class.getName()).log(Level.INFO, "Player "+ply.getName()+"'s birthday is null, skipping");
            }
            return player;

    }
    
    /**
     * Returns uuid or null if exception occurs.
     * @param ply
     * @param winner
     * @param duration
     * @return uuid
     */
    public static String postHighscore(tuwien.big.formel0.entities.Player ply, String winner, BigInteger duration){
        
        try {
            //create parameters.
            HighScoreRequestType req = new HighScoreRequestType();
            
            TournamentType tournament = new TournamentType();
           
            
            //PLAYERS
            TournamentType.Players players = new TournamentType.Players();
            TournamentType.Players.Player p = PlayerToXMLPlayer(ply);
            players.getPlayer().add(p);
            tournament.setPlayers(players);
            
            
            //Dates
            GregorianCalendar gc = new GregorianCalendar(); //Current Time
            XMLGregorianCalendar now = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
            tournament.setStartDate(now);
            tournament.setEndDate(now);
            tournament.setRegistrationDeadline(now);           
            
            
            //rounds
            TournamentType.Rounds rounds = new TournamentType.Rounds();
            TournamentType.Rounds.Round round = new TournamentType.Rounds.Round();
            round.setNumber(0);
                       
            //rounds-game
            GameType game = new GameType();
            
            at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.GameType.Players.Player ply_game = new at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.GameType.Players.Player();
            ply_game.setRef(p.getUsername());
            
            at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.GameType.Players game_players = new at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.GameType.Players();
            game_players.getPlayer().add(ply_game);
            
            game.setPlayers(game_players);
            
            game.setDate(now);
            game.setStatus("finished");
            game.setWinner(winner);
            game.setDuration(duration);

            round.getGame().add(game);
            rounds.getRound().add(round);
            tournament.setRounds(rounds);
                
            DescriptionType desc = new DescriptionType();
            tournament.setDescription(desc);
            
            req.setUserKey("34EphAp2C4ebaswu");
            req.setTournament(tournament);
            
            
            try { 
               String ret = endpoint.publishHighScore(req);
               return ret;
            } catch (Failure ex) {
                Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, ex.toString());
                //Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, ex.getMessage());
                //Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, ex.getFaultInfo().toString());
                Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, ex.getFaultInfo().getDetail());
                Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, ex.getFaultInfo().getReason());
                Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, ex.getFaultInfo().getCode());
                return null;
            } catch (Exception ex){ 
                Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, null, ex);
                Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, null, ex.getMessage());
                return null;
            } 
            
        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (ParseException ex) {
            Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (Exception ex){
             Logger.getLogger(HighscorePublisher.class.getName()).log(Level.SEVERE, null, ex);
             return null;
        }
    }
    
    
    
}
